<template>
  <div>
    <el-dialog :title="isEdit?'编辑部门':'新增部门'" :visible="showDialog" @close="close">
      <el-form ref="ruleForm" :model="form" :rules="ruleForm">
        <el-form-item label="部门名称" label-width="150px" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" label-width="150px" prop="code">
          <el-input v-model="form.code" autocomplete="off" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" label-width="150px" prop="managerId">
          <el-select v-model="form.managerId" placeholder="部门负责人">
            <!-- <el-option label="区域一" value="shanghai" /> -->
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce" label-width="150px">
          <el-input v-model="form.introduce" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确认{{ isEdit?'编辑':'新增' }}</el-button>
        <el-button @click="close">取 消</el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
import { getUserSimpleRequest, addDepartmentRequest, getDepartmentDetailRequest, editDepartmentRequest } from '@/api/department'
export default {
  name: 'AddEdit',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    departmentList: {
      type: Array,
      default: () => {
        return []
      }
    },
    currentId: {
      type: [Number, String],
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 部门名自定义校验
    const validatorName = (rules, value, callback) => {
      let res = cloneDeep(this.departmentList)
      if (this.isEdit) {
        res = res.filter(item => item.id !== this.currentId)
      }
      if (res.some(item => item.name === value)) {
        callback(new Error('部门名重复'))
      } else {
        callback()
      }
    }
    // 部门编码自定义校验
    const validatorCode = (rules, value, callback) => {
      let res = cloneDeep(this.departmentList)
      if (this.isEdit) {
        res = res.filter(item => item.id !== this.currentId)
      }
      if (res.some(item => item.name === value)) {
        callback(new Error('部门编码重复'))
      } else {
        callback()
      }
    }
    return {
      // 表单
      form: {
        name: '',
        code: '',
        introduce: '',
        managerId: '',
        pid: ''

      },
      // 负责人列表
      managerList: [],
      // 自定义校验
      ruleForm: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称是2-10位', trigger: ['blur', 'change'] },
          { validator: validatorName, trigger: 'change' }],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码是2-10位', trigger: ['blur', 'change'] },
          { validator: validatorCode, trigger: 'change' }],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '部门名称是1-100位', trigger: 'blur' }]

      }
    }
  },
  watch: {
    // 这里不需要写箭头函数
    isEdit(newVal, oldVal) {
      console.log(newVal, oldVal)
      if (newVal) {
        // 凡是看到this，就要小心thsi指向混乱问题
        this.getDepartmentDetail()
      }
    }
  },
  created() {
    this.getUserSimpleTMP()
  },
  methods: {
    // 关闭弹窗
    close() {
      this.$emit('update:showDialog', false)
      // 解决2次点击编辑,第二次不回显的bug
      this.$emit('update:isEdit', false)
      // 清空表单原始数据+清空表单校验
      this.$refs.ruleForm.resetFields()
      // form数据结构还原
      this.form = this.$options.data().form
      // 第二种数据结构还原
      // this.form = {
      //   name: '',
      //   code: '',
      //   introduce: '',
      //   managerId: '',
      //   pid: ''
      // }
    },
    // 获取负责人列表
    async getUserSimpleTMP() {
      const res = await getUserSimpleRequest()
      console.log(res)
      this.managerList = res.data
    },
    // 获取编辑框回显数据
    async getDepartmentDetail() {
      const res = await getDepartmentDetailRequest(this.currentId)
      console.log(res)
      this.form = res.data
    },
    // 提交表单
    submitForm() {
      this.$refs.ruleForm.validate(async valid => {
        console.log(this.form)
        if (valid) {
          // console.log('hhhh')
          // 发送添加部门请求
          if (this.isEdit) {
            await editDepartmentRequest(this.form)
          } else { await addDepartmentRequest({ ...this.form, pid: this.currentId }) }
          this.close()
          // 添加成功提示
          this.$message({
            message: `${this.isEdit ? '编辑' : '新增'}部门成功`,
            type: 'success'
          })
          // 刷新列表
          this.$emit('addSuccess')
        }
      })
    }
  }

}
</script>

<style>

</style>
